﻿using System;
using System.Text;
using DotNet.Configure;
using System.Windows.Forms;

namespace CfgDataManager
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            var a = ConfigureManager.Instance;
            cbDtype.SelectedIndex = 0;
            cbNType.SelectedIndex = 0;
            tbFileLoc.Text = ConfigureManager.Instance.ConfigPath;
            btnRefresh_Click(sender,e);
        }
        
        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            var dr = openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                string filepath = openFileDialog1.FileName;
                tbFileLoc.Text = filepath;
                ConfigureManager.Instance.ConfigPath = filepath;
                btnRefresh_Click(sender,e);
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            tviewList.Nodes.Clear();
            tsProcessbar.Value = 1;
            ConfigureManager.Instance.ReLoad();
            var temp = ConfigureManager.Instance.GetList();
            foreach (ConfigValue value in temp)
            {
                tviewList.Nodes.Add(new TreeNode(value.Name,
                    new TreeNode[] { new TreeNode("值："+value.Value), new TreeNode("类型："+value.DataType), }));

            }
            tsProcessbar.Value = tsProcessbar.Maximum;
        }
        
        private void tviewList_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var p = e.Node.Parent;
            if (p == null)
            {
                var key = e.Node.Text;
                tbName.Text = key;
                var cfg = ConfigureManager.Instance.Get(key);
                cbDtype.Text = cfg.DataType.FullName;
                
                cbNType.SelectedIndex = (int) cfg.NodeType;
                if (cfg.NodeType == NodeType.Array)
                {
                    StringBuilder sb = new StringBuilder();
                    var trans = (Array)cfg.Value;
                    for (int i = 0; i < trans.Length; i++)
                    {
                        sb.Append(trans.GetValue(i));
                        sb.Append(Environment.NewLine);
                    }
                    tbValues.Text = sb.ToString().TrimEnd(Environment.NewLine.ToCharArray());
                }
                else
                {
                    tbValues.Text = cfg.Value.ToString();
                }
            }
        }

        private void tbValues_TextChanged(object sender, EventArgs e)
        {
            cbNType.SelectedIndex = tbValues.Text.Contains(Environment.NewLine) ? 1 : 0;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (Check())
            {
                //保存
                ConfigureManager.Instance.Set(new ConfigValue(tbName.Text, GetValue(), GetCfgType(),
                    (NodeType) cbNType.SelectedIndex));
            }
        }
        
        private void btnMdify_Click(object sender, EventArgs e)
        {
            if (Check())
            {
                //修改
                ConfigureManager.Instance.Set(new ConfigValue(tbName.Text, GetValue(), GetCfgType(),
                    (NodeType)cbNType.SelectedIndex));
            }
        }

        bool Check()
        {
            bool pass = true;
            if (tbName.Text.Trim() + "" == "")
            {
                tsMsg.Text = "名称不能为空";
                pass = false;
            }
            else
            {
                if (tbValues.Text.Trim() + "" == "")
                {
                    tsMsg.Text = "值不能为空";
                    pass = false;
                }
            }
            return pass;
        }
        /// <summary>
        /// 获取用户设置的数据类型
        /// </summary>
        Type GetCfgType()
        {
            string typename = cbDtype.Text;
            return Type.GetType(typename);
        }
        /// <summary>
        /// 获取用户设置的数值
        /// </summary>
        /// <returns></returns>
        object GetValue()
        {
            object obj = new object();
            tsProcessbar.Value = 1;
            if (cbNType.SelectedIndex == 1)
            {
                try
                {
                    Type t = GetCfgType();
                    tbValues.Text = tbValues.Text.Trim().TrimEnd(Environment.NewLine.ToCharArray());
                    while (tbValues.Text.IndexOf(Environment.NewLine + Environment.NewLine, StringComparison.InvariantCultureIgnoreCase) > -1)
                    {
                        tbValues.Text = tbValues.Text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
                    }
                    
                    int len = tbValues.Lines.Length;
                    var trans = Array.CreateInstance(t, len);

                    for (int i = 0; i < len; i++)
                    {
                        var value = tbValues.Lines[i];
                        var v = ConfigureManager.Instance.ConvertObject(value, t);
                        trans.SetValue(v, i);
                    }
                    obj = trans;
                }
                catch (Exception ex)
                {
                    tsMsg.Text = ex.Message;
                }
            }
            else
            {
                tbValues.Text = tbValues.Text.Trim().TrimEnd("\r\n".ToCharArray());
                obj = tbValues.Text;
            }
            tsProcessbar.Value = 100;
            return obj;
        }
    }
}
